'use strict';

module.exports = app => {
  const mongoose = app.mongoose;
  const Schema = mongoose.Schema;

  const TopicSchema = new Schema({
    title: {type: String, required: true},
    content: {type: String, required: true},
    author_id: {type: String, required: true},
    author_name: {type: String, required: true},
    author_avatar: {type: String, required: true},
    tab: {type: String, required: true},
    top: {type: Boolean, default: false}, // 置顶帖
    good: {type: Boolean, default: false}, // 精华帖
    lock: {type: Boolean, default: false}, // 被锁定文章
    reply_count: {type: Number, default: 0},
    visit_count: {type: Number, default: 0},
    collect_count: {type: Number, default: 0},
    last_reply: {type: String},
    last_reply_at: {type: Date, default: Date.now},
    boards: {type: [String], default: []},
    tags: {type: [String], default: []},
    source: {type: String},
    original_url: {type: String},
    is_public: {type: Boolean, default: true},
    topic_type: {type: String},
    pic: {type: String},
    pics: {type: Array, default: undefined},
    intro: {type: String},
    is_video: {type: Boolean, default: false},
    video_length: {type: String},
  }, {timestamps: true});


  TopicSchema.virtual('defaultLink').get(function () {
    // 如果实体中已经有 'link' 字段，则直接使用它
    if (this.original_url) {
      return this.original_url;
    }
    // 否则，根据文章的 _id 生成链接
    return `/topic/${this._id}`;
  });

  // 新增索引
  TopicSchema.index({title: 1, is_public: 1, tab: 1, last_reply_at: -1}, {background: true});
  TopicSchema.index({is_public: 1, tab: 1, last_reply_at: -1}, {background: true});


  TopicSchema.index({createdAt: -1}, {background: true});
  TopicSchema.index({boards: 1}, {background: true});
  TopicSchema.index({tags: 1}, {background: true});
  TopicSchema.index({top: -1, last_reply_at: -1}, {background: true});
  TopicSchema.index({title: 1, updatedAt: -1}, {background: true});
  TopicSchema.index({tab: 1, title: 1, updatedAt: -1}, {background: true});
  TopicSchema.index({tab: 1, boards: 1, updatedAt: -1}, {background: true});
  TopicSchema.index({author_name: 1, createdAt: -1}, {background: true});
  TopicSchema.index({author_id: 1, tab: 1, createdAt: -1}, {background: true});
  TopicSchema.index({author_id: 1, tab: 1, title: 1, createdAt: -1}, {background: true});
  TopicSchema.index({author_id: 1, tab: 1, boards: 1, createdAt: -1}, {background: true});
  TopicSchema.index({author_id: 1, last_reply_at: -1}, {background: true});

  TopicSchema.index({original_url: 1, tab: 1}, {
      unique: true,
      background: true,
      partialFilterExpression: {source: {$exists: true}, original_url: {$exists: true}}
    }
  );

  TopicSchema.index({title: 1, author_name: 1, tab: 1}, {unique: true, background: true});

  TopicSchema.on('index', function (err) {
    if (err) console.error('Mongoose create index error: ', err);
  });

  return mongoose.model('Topic', TopicSchema, 'topics');
};
